﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using MySql.Data.MySqlClient;

using BMS.Models;
using BMS.Utilities;

namespace BMS.Models.DataAccess
{
    public class DatabaseAccess
    {
        private String connectionString = "Server=" + Configuration.DatabaseServer 
            + ";Database=" + Configuration.DatabaseName
            + ";Uid=" + Configuration.DatabaseUserName
            + ";Pwd=" + Configuration.DatabasePassword + ";";
        public MySqlConnection connection = new MySqlConnection();

        public void DBConnectionOn()
        {
            connection = new MySqlConnection(connectionString);
            connection.Open();
        }

        public void DBConnectionOff()
        {
            if(connection.State == ConnectionState.Open)
                connection.Close();
        }

        

        public ConfigurationModel GetConfigurationItem(String configKey)
        {
            ConfigurationModel configItem = new ConfigurationModel();
            String query = "SELECT * FROM " + Configuration.DatabaseName + ".configuration WHERE vc_fldConfigKey = '" + configKey + "'";

            DBConnectionOn();

            try
            {
                MySqlCommand cmd = new MySqlCommand(query, connection);
                MySqlDataReader dataReader = cmd.ExecuteReader();

                while (dataReader.Read())
                {
                    configItem.ConfigurationKey = dataReader["vc_fldConfigKey"] + "";
                    configItem.ConfigurationValue = dataReader["vc_fldConfigValue"] + "";
                }
            }
            catch (Exception e)
            {
                throw;
            }
            finally
            {
                DBConnectionOff();
            }
            return configItem;
        }
    }
}